//
//  PeriodViewController.swift
//  SmallParts
//
//  Created by 航汇聚 on 2019/12/9.
//  Copyright © 2019 BellaZhou. All rights reserved.
//

import UIKit

class PeriodViewController: UIViewController {
    @IBOutlet weak var childContentView: UIView!
    @IBOutlet weak var collectionView: UICollectionView!
    var collectionViews: NSMutableArray?
    let requestObjectType: String = "media"
    var requestPageIndex: Int = 1
    var requestPageSize: Int = 21
    var requestDomainID: String = ""
    var periodsArray: [SearchMediaItemModel]?
    var selectedDomains: [DomainItemObject]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let allItem = DomainItemObject(_id: "0", name: "全部")
        self.selectedDomains = [allItem]
        self.collectionView.reloadData()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.addScrollChildView()
    }

    func addScrollChildView() -> Void {
        let scrollView = UIScrollView.init(frame: self.childContentView.bounds)
        var hasScrollView: Bool = false
        for view in self.childContentView.subviews {
            if view.isKind(of: UIScrollView.self) {
                hasScrollView = true
            }
        }
        if !hasScrollView {
            self.childContentView.addSubview(scrollView)
        }
        let scrollChildContentView = UIView.init()
        scrollView.addSubview(scrollChildContentView)
        
        scrollChildContentView.frame = CGRect(x: 0, y: 0, width: CGFloat(integerLiteral: self.selectedDomains!.count)*scrollView.bounds.size.width, height: scrollView.bounds.size.height)
        if (self.collectionViews != nil) && self.collectionViews!.count == self.selectedDomains?.count {
            return
        }
        self.collectionViews = NSMutableArray.init()
        for index in 0...11 {
            let layout = UICollectionViewFlowLayout.init()
            layout.scrollDirection = UICollectionView.ScrollDirection.vertical
            layout.itemSize = CGSize(width: scrollView.bounds.size.width/3 - 12, height: 188)
            layout.sectionInset = UIEdgeInsets(top: 0, left: 8, bottom: 8, right:   12)
            layout.minimumLineSpacing = 4
            layout.minimumInteritemSpacing = 4
            let childCollectitonView = UICollectionView.init(frame: CGRect(x: CGFloat(index)*scrollView.bounds.size.width, y: 0, width: scrollView.bounds.size.height, height: scrollView.bounds.size.height), collectionViewLayout: layout)
            self.collectionViews?.add(childCollectitonView)
            childCollectitonView.showsVerticalScrollIndicator = false
            childCollectitonView.showsHorizontalScrollIndicator = false
            scrollChildContentView.addSubview(childCollectitonView)
            childCollectitonView.backgroundColor = UIColor.white
            childCollectitonView.dataSource = self
            childCollectitonView.register(UINib(nibName: "PeriodCollectionCell", bundle: nil), forCellWithReuseIdentifier: "periodCell")
        }
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.contentSize = CGSize(width: CGFloat(integerLiteral: self.selectedDomains!.count)*scrollView.bounds.size.width, height: 0)
        scrollView.isPagingEnabled = true
        self.requestNumInfo(indexOfChildCollection: 0, id: self.requestDomainID, pageIndex: self.requestPageIndex, pageSize: self.requestPageSize, object: self.requestObjectType)
    }
    func requestNumInfo(indexOfChildCollection: Int, id: String, pageIndex: Int, pageSize:Int, object:String) {
        let upload = UploadingData.init()
        upload.uploadData("http://api.cqvip.com/qikanapp/GetSearch.ashx", "domainid=\(id)&pageindex=\(pageIndex)&pagesize=\(pageSize)&object=\(object)", .post)
        upload.success = { (data, urlString) -> () in
             let result = try? JSONDecoder().decode(SearchMediaDictModel.self, from: data!)
            self.periodsArray = result?.result.list
            (self.collectionViews![indexOfChildCollection] as! UICollectionView).reloadData()
        }
    }
}

extension PeriodViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == self.collectionView {
            return self.selectedDomains == nil ? 0 : self.selectedDomains!.count
        }else {
            return self.periodsArray == nil ? 0 : self.periodsArray!.count
        }
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == self.collectionView {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "labelCell", for: indexPath) as! LabelCollectCell
            cell.labelButton.setTitle(self.selectedDomains![indexPath.row].name, for: .normal)
            cell.delegate = self
            return cell
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "periodCell", for: indexPath) as! PeriodCollectionCell
            let periodInfo = self.periodsArray![indexPath.row]
            cell.titleLabel.text = periodInfo.media.isEmpty ? "暂无" : periodInfo.media
            DispatchQueue.global().sync {
                let imgURL = URL(string: "http://image.cqvip.com/vip1000/qk/\(periodInfo.gch)/\(periodInfo.gch).jpg")
                if (imgURL != nil) {
                    let downloadTask = URLSession.shared.dataTask(with: imgURL!) { (data, response, error) in
                        DispatchQueue.main.async {
                            cell.coverImgView.image = UIImage(data: data!)
                        }
                    }
                    downloadTask.resume()
                }
            }
            return cell
        }
    }
}
extension PeriodViewController: LabelCollectCellDelegate {
    func touchAction(with cell: LabelCollectCell) {
        
    }
}
class LabelCollectCell: UICollectionViewCell {
    var delegate: LabelCollectCellDelegate?
    @IBOutlet weak var labelButton: UIButton!
    @IBAction func touchAction(_ sender: UIButton) {
        if self.delegate != nil {
            self.delegate?.touchAction(with: self)
        }
    }
}
protocol LabelCollectCellDelegate {
    func touchAction(with cell: LabelCollectCell) -> Void
}
